import os
from typing import Any, Dict
import requests
from mcp.server.fastmcp import FastMCP


# 创建 MCP Server 实例
mcp = FastMCP("Demo")


""" 通过 mcp.tool() 装饰器将 current_weather 函数定义为一个 MCP 工具
它接受一个城市名参数，返回该城市的当前天气信息 """
@mcp.tool()
def current_weather(city: str) -> Dict[str, Any]:
    api_key = os.getenv("SENIVERSE_API_KEY")
    if not api_key:
        raise Exception("SENIVERSE_API_KEY not set")

    try:
        # 使用 requests 库发送 HTTP 请求到 Seniverse API 获取天气数据
        weather_response = requests.get(
            "https://api.seniverse.com/v3/weather/now.json",
            params={
                "key": api_key,
                "location": city,
                "language": "en",
                "unit": "c"
            }
        )
        weather_response.raise_for_status()
        data = weather_response.json()
        results = data["results"]

        if not results:
            return {"error": f"Could not find weather data for city: {city}"}

        # 将 API 返回的 JSON 返回给 MCP 客户端
        return results
    # 错误处理，包括 API Key 未设计、API 请求失败等情况
    except requests.exceptions.RequestException as e:
        error_message = f"Weather API error: {str(e)}"
        if hasattr(e, "response") and e.response is not None:
            try:
                error_data = e.response.json()
                if 'message' in error_data:
                    error_message = f"Weather API error: {error_data['message']}"
            except ValueError:
                pass
        return {"error": error_message}
